<?php

namespace App\Services;

use App\Models\Menu;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class MenuService
{
    /**
     * 创建菜单
     *
     * @param array $data
     * @return Menu
     */
    public function create(array $data): Menu
    {
        return Menu::create([
            'parent_id' => $data['parent_id'] ?? 0,
            'title' => $data['title'],
            'name' => $data['name'] ?? null,
            'path' => $data['path'] ?? null,
            'component' => $data['component'] ?? null,
            'icon' => $data['icon'] ?? null,
            'type' => $data['type'],
            'permission' => $data['permission'] ?? null,
            'status' => $data['status'],
            'sort' => $data['sort'] ?? 0,
            'hidden' => $data['hidden'] ?? 0,
            'keep_alive' => $data['keep_alive'] ?? 0,
            'remark' => $data['remark'] ?? null,
        ]);
    }

    /**
     * 更新菜单
     *
     * @param Menu $menu
     * @param array $data
     * @return Menu
     */
    public function update(Menu $menu, array $data): Menu
    {
        $menu->update([
            'parent_id' => $data['parent_id'] ?? 0,
            'title' => $data['title'],
            'name' => $data['name'] ?? null,
            'path' => $data['path'] ?? null,
            'component' => $data['component'] ?? null,
            'icon' => $data['icon'] ?? null,
            'type' => $data['type'],
            'permission' => $data['permission'] ?? null,
            'status' => $data['status'],
            'sort' => $data['sort'] ?? 0,
            'hidden' => $data['hidden'] ?? 0,
            'keep_alive' => $data['keep_alive'] ?? 0,
            'remark' => $data['remark'] ?? null,
        ]);

        return $menu;
    }

    /**
     * 删除菜单
     *
     * @param Menu $menu
     * @return bool
     * @throws \Exception
     */
    public function delete(Menu $menu): bool
    {
        if (Menu::hasChildren($menu->id)) {
            throw new \Exception('存在子菜单，无法删除');
        }

        return $menu->delete();
    }

    /**
     * 获取用户菜单路由
     *
     * @param User $user
     * @return array
     */
    public function getUserRoutes(User $user): array
    {
        $menus = Menu::enabled()
            ->where('type', '!=', Menu::TYPE_BUTTON)
            ->orderBy('sort')
            ->get();

        // 使用权限服务过滤菜单
        $permissionService = app(\App\Services\PermissionService::class);
        $menusArray = $menus->map(function ($menu) {
            return [
                'id' => $menu->id,
                'parent_id' => $menu->parent_id,
                'title' => $menu->title,
                'name' => $menu->name,
                'path' => $menu->path,
                'component' => $menu->component,
                'icon' => $menu->icon,
                'type' => $menu->type,
                'permission' => $menu->permission,
                'status' => $menu->status,
                'sort' => $menu->sort,
                'hidden' => $menu->hidden,
                'keep_alive' => $menu->keep_alive,
                'remark' => $menu->remark,
            ];
        })->toArray();
        
        $menusTree = $this->buildMenuTree($menusArray, 0);
        
        return $permissionService->filterMenusByPermission($menusTree, $user);
    }

    /**
     * 构建菜单树
     *
     * @param array $menus
     * @param int $parentId
     * @return array
     */
    protected function buildMenuTree(array $menus, int $parentId): array
    {
        $tree = [];
        foreach ($menus as $menu) {
            if ($menu['parent_id'] == $parentId) {
                $children = $this->buildMenuTree($menus, $menu['id']);
                if ($children) {
                    $menu['children'] = $children;
                }
                $tree[] = $menu;
            }
        }
        return $tree;
    }
}

